//The MIT License

//Copyright (c) 2009 Lluis Sanchez, Nick Darnell

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

using System;
using System.Collections;
using System.Reflection.Emit;
using System.Reflection;
using System.Xml;

using NUnit.Framework;

namespace Polymorph.Test
{
    [TestFixture]
    public class SerializerTestFixture
    {
        [Test]
        public void SerializerTest()
        {
            DynamicMethod ser = GenerateSerializer(typeof(Data));
            XmlWriter writer = new XmlTextWriter(Console.Out);

            ser.Invoke(null, new object[] { new Data(), writer });
        }

        public static DynamicMethod GenerateSerializer(Type targetType)
        {
            CodeDynamicMethod method = new CodeDynamicMethod(typeof(Data), "Serialize", typeof(void), new Type[] { typeof(Data), typeof(XmlWriter) }, true);
            CodeBuilder cb = method.CodeBuilder;

            //CodeValueReference obj = cb.DeclareVariable(targetType, method.GetArg(0).CastTo(targetType));
            cb += method.GetArg(1).Call("WriteStartElement", Exp.Literal(targetType.Name));

            foreach (FieldInfo field in targetType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
                cb += method.GetArg(1).Call("WriteElementString", Exp.Literal(field.Name), method.GetArg(0)[field].CallToString());

            cb += method.GetArg(1).Call("WriteEndElement");

            Console.WriteLine(method.PrintCode());

            return method.Generate();
        }
    }

    public class Data
    {
        int a = 2;
        string b = "hi!";
        byte c = 44;
    }
}